package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.config.ExpressConfig;
import com.cskaoyan.bean.order.bo.*;
import com.cskaoyan.bean.order.vo.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.util.JsonUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.lang.System;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    OrderGoodsMapper orderGoodsMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    CouponUserMapper couponUserMapper;
    @Autowired
    CartService cartService;
    @Autowired
    AdminConfigService configService;
    @Autowired
    CartServiceImpl cartService2;


    @Override
    public OrderListVo getOrderList(OrderListBo listBo) {
        OrderListVo orderListVo = new OrderListVo();

        Integer page = listBo.getPage();
        Integer limit = listBo.getLimit();
        String order = listBo.getOrder(); // 分页顺序
        String sort = listBo.getSort();
        String orderSn = listBo.getOrderSn();
        Integer orderStatusArray = listBo.getOrderStatusArray();
        Integer userId = listBo.getUserId();

        PageHelper.startPage(page, limit);//调用分页插件,查询时会进行拼接
        //获得分页信息
        PageInfo<OrderListVo> orderListVosPageInfoInfo = new PageInfo<>();
        long total = orderListVosPageInfoInfo.getTotal();

//         排序信息
        OrderExample orderExample = new OrderExample();
        orderExample.setOrderByClause(sort + " " + order);
        OrderExample.Criteria criteria = orderExample.createCriteria();
//         查询
        criteria.andDeletedEqualTo(false);
        if (!"0".equals(orderSn) && orderSn != null) {
            criteria.andOrderSnEqualTo(orderSn);
        }
        if (orderStatusArray != null && orderStatusArray != 0) {
            criteria.andOrderStatusEqualTo(orderStatusArray);
        }
        if (userId != null && userId != 0) {
            criteria.andUserIdEqualTo(userId);
        }
        List<Order> orders = orderMapper.selectByExample(orderExample);
//        List<Order> orders = orderMapper.selectOrders(orderSn,orderStatusArray,userId,sort,order);

        // pojo 转 vo
        orderListVo.setTotal(total);
        orderListVo.setItems(orders);

        return orderListVo;
    }


    /**
     * 获取订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderDetailVo getOrderDetail(Integer id) {
        Order order = orderMapper.selectByPrimaryKey(id);
        // pojo 转 vo
        OrderDetailVo orderDetailVo = new OrderDetailVo(); // vo

        Order orderBean = orderMapper.selectByPrimaryKey(order.getId());// 订单信息
        User userBean = userMapper.selectByPrimaryKey(order.getUserId()); // 用户信息
        List<OrderGoods> orderGoodsBeanList = orderGoodsMapper.selectByUserId(order.getId());//商品信息

        orderDetailVo.setOrder(orderBean);
        orderDetailVo.setOrderGoods(orderGoodsBeanList);
        orderDetailVo.setUser(userBean);

        return orderDetailVo;
    }

    /**
     * todo 退款 : 网上一直退款失败,先按删除订单做
     *
     * @param refundBo
     * @return
     */
    @Override
    public Integer refund(OrderRefundBo refundBo) {
        Integer orderId = refundBo.getOrderId();
        int effectedRows = orderMapper.cancelOrder(orderId);
        return effectedRows;
    }

    /**
     * 设置快递公司和快递编号, 更改状态码为 301
     *
     * @param shipBo
     * @return
     */
    @Override
    public Integer AddShip(OrderShipBo shipBo) {
        int effectedRows = orderMapper.updateShipInfo(shipBo.getShipSn(), shipBo.getShipChannel(), shipBo.getOrderId());
        return effectedRows;
    }


    /**
     * 显示wx订单信息
     *
     * @param showType 根据订单状态显示
     * @param page     页数
     * @param size     第几个
     * @param userId
     * @return
     */
    @Override
    public WXOrderListVo getWXOrderList(Integer showType, Integer page, Integer size, Integer userId) {
        // vo
        WXOrderListVo wxOrderListVo = new WXOrderListVo();
        // vo 成员变量: 订单信息
        List<WXListData> wxListDataList = new ArrayList<>();

        //调用分页插件,查询时会进行拼接
        PageHelper.startPage(page, size);
        // 查询order表出所有数据
        List<Order> orders = getOrderList(userId);
        // 然后分别取出放到四个list中
        List<Order> orders_All = new ArrayList<>();
        List<Order> orders_101 = new ArrayList<>();
        List<Order> orders_201 = new ArrayList<>();
        List<Order> orders_301 = new ArrayList<>();
        List<Order> orders_401 = new ArrayList<>();

        for (Order order : orders) {
            orders_All.add(order);
            //  根据状态分类
            if (order.getOrderStatus() == 101) {
                orders_101.add(order);
            } else if (order.getOrderStatus() == 201) {
                orders_201.add(order);
            } else if (order.getOrderStatus() == 301) {
                orders_301.add(order);
            } else if (order.getOrderStatus() == 401 || order.getOrderStatus() == 402) {
                orders_401.add(order);
            }
        }
        // 根据请求参数,去转换不同的list, pojo 转 vo
        if (showType == 1) {
            transferToGoodsList(orders_101, wxListDataList);
        } else if (showType == 2) {
            transferToGoodsList(orders_201, wxListDataList);
        } else if (showType == 3) {
            transferToGoodsList(orders_301, wxListDataList);
        } else if (showType == 4) {
            transferToGoodsList(orders_401, wxListDataList);
        } else {
            transferToGoodsList(orders_All, wxListDataList);
        }

        // vo 赋值
        long total = wxListDataList.size();
        long totalPages = total / size + 1;
        wxOrderListVo.setCount(total);
        wxOrderListVo.setTotalPages(totalPages);
        wxOrderListVo.setData(wxListDataList);
        return wxOrderListVo;
    }

    private List<Order> getOrderList(Integer userId) {
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andDeletedEqualTo(false).andUserIdEqualTo(userId);
        // 执行查询
        List<Order> orders = orderMapper.selectByExample(orderExample);
        return orders;
    }


    /**
     * 订单详情展示
     *
     * @param id
     * @return
     */
    @Override
    public WXOrderDetailVo getWXOrderDetailList(Integer id) {
        WXOrderDetailVo wxOrderDetailVo = new WXOrderDetailVo();
        // vo 成员变量 订单内商品信息
        List<OrderGoods> orderGoods = new ArrayList<>();
        // vo 成员变量 订单信息
        WXOrderInfoBean wxOrderInfoBean = new WXOrderInfoBean();
        // 获取状态信息的map
        HashMap<Integer, String> statusMap = getIntegerStringHashMap();

        // 查出order和orderGoodsList所有数据
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(id).andDeletedEqualTo(false);
        Order order = orderMapper.selectByPrimaryKey(id);
        List<OrderGoods> orderGoodsList = getOrderGoodsList();

        // orderGoods 赋值
        for (OrderGoods goods : orderGoodsList) {
            if (goods.getOrderId().equals(order.getId())) {
                orderGoods.add(goods);
            }
        }

        //填充wxOrderInfoBean
        // 获取订单权限
        HandleOptionBean handleOptionBean = getHandleOptionBean(order);
        wxOrderInfoBean.setHandleOption(handleOptionBean);
        wxOrderInfoBean.setConsignee(order.getConsignee());
        wxOrderInfoBean.setAddress(order.getAddress());
        wxOrderInfoBean.setAddTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getAddTime()));
        wxOrderInfoBean.setOrderSn(order.getOrderSn());
        wxOrderInfoBean.setActualPrice(order.getActualPrice());
        wxOrderInfoBean.setMobile(order.getMobile());
        wxOrderInfoBean.setExpCode(order.getShipSn());
        wxOrderInfoBean.setOrderStatusText(statusMap.get(order.getOrderStatus()));
        wxOrderInfoBean.setExpNo(order.getShipChannel()); // expNo不知道是啥
        wxOrderInfoBean.setGoodsPrice(order.getGoodsPrice());
        wxOrderInfoBean.setCouponPrice(order.getCouponPrice());
        wxOrderInfoBean.setId(order.getId());
        wxOrderInfoBean.setFreightPrice(order.getFreightPrice());


        wxOrderDetailVo.setOrderGoods(orderGoods);
        wxOrderDetailVo.setOrderInfo(wxOrderInfoBean);

        return wxOrderDetailVo;
    }

    @Override
    public int cancelWXOrder(WXOrderIdBo cancelBo) {
        Integer orderId = cancelBo.getOrderId();
        Timestamp ts = getCurrentTime();
        int effectedRows = orderMapper.changeStatusById(orderId, ts, 102);
        return effectedRows;
    }

    @Override
    public int refundWXOrder(WXOrderIdBo refundBo) {
        Integer orderId = refundBo.getOrderId();
        Timestamp ts = getCurrentTime();

        int effectedRows = orderMapper.changeStatusById(orderId, ts, 202);
        return effectedRows;
    }

    private Timestamp getCurrentTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());
        return Timestamp.valueOf(time);
    }

    @Override
    public int deleteWXOrder(WXOrderIdBo deleteBo) {
        Integer orderId = deleteBo.getOrderId();
        Timestamp ts = getCurrentTime();
        int effectedRows = orderMapper.ChangeDeleteStatusById(orderId, ts, 102);
        return effectedRows;
    }

    @Override
    public int confirmWXOrder(WXOrderIdBo confirmBo) {
        Integer orderId = confirmBo.getOrderId();
        Timestamp ts = getCurrentTime();
        int effectedRows = orderMapper.changeStatusById(orderId, ts, 401);
        return effectedRows;
    }

    @Override
    public OrderGoods getWXGoods(Integer orderId, Integer goodsId) {
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andDeletedEqualTo(false).andGoodsIdEqualTo(goodsId).andOrderIdEqualTo(orderId);
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);
        return orderGoodsList.get(0);
    }

    /**
     * @param submitBo
     * @return
     */
    @Override
    @Transactional
    public int submitWXOrder(WXOrderSubmitBo submitBo) {
        Integer addressId = submitBo.getAddressId();
        Integer cartId = submitBo.getCartId();
        // 获得优惠券
        Integer couponId = submitBo.getCouponId();
        BigDecimal coupondPrice = new BigDecimal(0);
        if (couponId != null) {
            Coupon coupond = couponMapper.selectByPrimaryKey(couponId);
            coupondPrice = coupond.getDiscount();
        }
        String message = submitBo.getMessage();
        int maxId = orderMapper.getMaxId();
        Integer grouponLinkId = submitBo.getGrouponLinkId(); // todo 团购没写, 暂时全写0
        Integer grouponRulesId = submitBo.getGrouponRulesId();

        User user = (User) SecurityUtils.getSubject().getPrincipal();
        List<Cart> carts = new ArrayList<>();
        if (cartId == 0) {
            carts = cartService.selectCartItem(user.getId(), null, true);
        } else {
            CartExample cartExample = new CartExample();
            CartExample.Criteria criteria = cartExample.createCriteria();
//            criteria.andDeletedEqualTo(false).andUserIdEqualTo(user.getId());
            criteria.andDeletedEqualTo(false).andIdEqualTo(cartId);
            carts= cartMapper.selectByExample(cartExample);
//            carts = carts1;



            Address address = addressMapper.selectByPrimaryKey(addressId);
            Timestamp createTime = getCurrentTime(); // 新增时间
            // pojo

            Order order = new Order();
            order.setConsignee(address.getName());
            order.setUserId(user.getId());
            order.setMobile(user.getMobile());
            order.setAddress(address.getAddress());
            order.setMessage(message);
            order.setCouponPrice(coupondPrice);
            order.setGrouponPrice(BigDecimal.valueOf(0));
            order.setAddTime(createTime);
            long timeMillis = System.currentTimeMillis();
            order.setOrderSn(String.valueOf(timeMillis)); // 自动生成订单号
            order.setOrderStatus(101);
            // 算商品总价格
            BigDecimal goodsPrice = new BigDecimal(0);
            int count=0;
            for (Cart cart : carts) {
                BigDecimal price = cart.getPrice();
                int i = price.intValue();
                count+=i;
//            goodsPrice = goodsPrice.add(price.multiply(BigDecimal.valueOf(cart.getNumber())));
            }
            goodsPrice= new BigDecimal(count);
            order.setGoodsPrice(goodsPrice);

            // 计算邮费
            BigDecimal freightPrice = new BigDecimal(0);
            try {
                freightPrice = cartService2.calcualteFreightPrice(goodsPrice);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
            order.setFreightPrice(freightPrice);

            // 计算总价
            order.setActualPrice(goodsPrice.add(freightPrice).subtract(coupondPrice));
            if (couponId != null) {
                couponUserMapper.useCoupon(user.getId(), couponId); // 更改优惠券信息
            }

            orderMapper.insertSelective(order);
            return order.getId();
        }



        Address address = addressMapper.selectByPrimaryKey(addressId);
        Timestamp createTime = getCurrentTime(); // 新增时间
        // pojo

        Order order = new Order();
        order.setConsignee(address.getName());
        order.setUserId(user.getId());
        order.setMobile(user.getMobile());
        order.setAddress(address.getAddress());
        order.setMessage(message);
        order.setCouponPrice(coupondPrice);
        order.setGrouponPrice(BigDecimal.valueOf(0));
        order.setAddTime(createTime);
        long timeMillis = System.currentTimeMillis();
        order.setOrderSn(String.valueOf(timeMillis)); // 自动生成订单号
        order.setOrderStatus(101);


        // 算商品总价格
        BigDecimal goodsPrice = new BigDecimal(0);
        int count=0;
        for (Cart cart : carts) {
            BigDecimal price = cart.getPrice();

            goodsPrice = goodsPrice.add(price.multiply(BigDecimal.valueOf(cart.getNumber())));

            // 向orderGoods中去insert
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setOrderId(order.getId());
            orderGoods.setGoodsName(cart.getGoodsName());
            orderGoods.setPicUrl(cart.getPicUrl());
            orderGoods.setAddTime(createTime);
            orderGoods.setOrderId(maxId);
            orderGoods.setPrice(cart.getPrice());
            orderGoods.setGoodsId(cart.getGoodsId());
            orderGoods.setNumber(cart.getNumber());

            // 查出ordergoods
            OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
            OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
            criteria.andDeletedEqualTo(false).andOrderIdEqualTo(maxId);
            orderGoodsMapper.insert(orderGoods);
        }
        goodsPrice= new BigDecimal(count);
        order.setGoodsPrice(goodsPrice);

        // 计算邮费
        BigDecimal freightPrice = new BigDecimal(0);
        try {
            freightPrice = cartService2.calcualteFreightPrice(goodsPrice);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        order.setFreightPrice(freightPrice);

        // 计算总价
        order.setActualPrice(goodsPrice.add(freightPrice).subtract(coupondPrice));
        if (couponId != null) {
            couponUserMapper.useCoupon(user.getId(), couponId); // 更改优惠券信息
        }

        orderMapper.insertSelective(order);

        return order.getId();
    }

    @Override
    @Transactional
    public int addWXContent(WXOrderContentBo contentBo) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String content = contentBo.getContent();
        Boolean hasPicture = contentBo.getHasPicture();
        Integer orderGoodsId = contentBo.getOrderGoodsId();
        Integer star = contentBo.getStar();
        OrderGoods goods = orderGoodsMapper.selectByPrimaryKey(orderGoodsId);
        List<String> picUrls = contentBo.getPicUrls();
        try {
            String jason = JsonUtils.toJason(picUrls);
            Timestamp ts = getCurrentTime();
            WXOrderCommentId commentId = new WXOrderCommentId();
            int effectedRows = orderMapper.addContent(content, hasPicture, goods.getGoodsId(), star, jason, ts, commentId, user.getId());
            // 评论后,在orderGoods表将content状态修改为comment表中的评论id
            OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
            OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setComment(commentId.getId());
            criteria.andDeletedEqualTo(false).andIdEqualTo(orderGoodsId);
            orderGoodsMapper.updateByExampleSelective(orderGoods, orderGoodsExample);
            return effectedRows;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return 0;
    }


    private List<WXListData> transferToGoodsList(List<Order> ordersList, List<WXListData> wxListDataList) {

        HashMap<Integer, String> statusMap = getIntegerStringHashMap();

        // goods中的order_id == order 中的 id
        // 查询出orderGoods表所有数据
        List<OrderGoods> orderGoodsList = getOrderGoodsList();

        for (Order order : ordersList) {
            // 对订单信息赋值
            WXListData wxListData = new WXListData();
            List<WXGoodsList> wxGoodsLists = new ArrayList<>();
            for (OrderGoods goods : orderGoodsList) {
                if (goods.getOrderId() == order.getId()) {
                    WXGoodsList wxGoodsList = new WXGoodsList();
                    wxGoodsList.setGoodsName(goods.getGoodsName());
                    wxGoodsList.setId(goods.getId());
                    wxGoodsList.setNumber(goods.getNumber());
                    wxGoodsList.setPicUrl(goods.getPicUrl());
                    wxGoodsLists.add(wxGoodsList);
                }
            }
            HandleOptionBean handleOptionBean = getHandleOptionBean(order);

            wxListData.setOrderStatusText(statusMap.get(order.getOrderStatus()));
            wxListData.setIsGroupin(false);
            wxListData.setGoodsList(wxGoodsLists);
            wxListData.setOrderSn(order.getOrderSn());
            wxListData.setHandleOption(handleOptionBean);
            wxListData.setActualPrice(order.getActualPrice());
            wxListData.setId(order.getId());
            wxListDataList.add(wxListData);
        }
        return wxListDataList;
    }

    /**
     * 订单状态map
     *
     * @return
     */
    private HashMap<Integer, String> getIntegerStringHashMap() {
        // 返回数据中 orderStatusTest 和数据库对应的关系
        HashMap<Integer, String> statusMap = new HashMap<>();
        statusMap.put(101, "未付款");
        statusMap.put(102, "已取消");
        statusMap.put(201, "已付款");
        statusMap.put(202, "退款中");
        statusMap.put(203, "已退款");
        statusMap.put(301, "已发货");
        statusMap.put(401, "已收货");
        statusMap.put(402, "已收货");
        return statusMap;
    }

    /**
     * orderList 全查询
     *
     * @return
     */
    private List<OrderGoods> getOrderGoodsList() {
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        // 订单商品信息
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);
        return orderGoodsList;
    }

    /**
     * 获得状态信息
     *
     * @param order
     * @return
     * 
     */
    private HandleOptionBean getHandleOptionBean(Order order) {
        HandleOptionBean handleOptionBean = new HandleOptionBean();
        Integer orderStatus = order.getOrderStatus();
        if (orderStatus == 101) {
            handleOptionBean.setCancel(true);
            handleOptionBean.setPay(true);
        } else if (orderStatus == 102) {
            handleOptionBean.setDelete(true);
        } else if (orderStatus == 201) {
            handleOptionBean.setRefund(true);
        } else if (orderStatus == 202) {
            handleOptionBean.setCancel(true);
            handleOptionBean.setDelete(true);
        } else if (orderStatus == 203) {
            handleOptionBean.setDelete(true);
        } else if (orderStatus == 301) {
            handleOptionBean.setConfirm(true);
        } else if (orderStatus == 401) {
            handleOptionBean.setComment(true);
            handleOptionBean.setDelete(true);
            handleOptionBean.setRebuy(true);
        } else if (orderStatus == 402) { // 用系统收货,来代表已评论,关闭评论的权限
            handleOptionBean.setDelete(true);
            handleOptionBean.setRebuy(true);
        }
        return handleOptionBean;
    }

}
